<template>
<div class="data-source">
    <el-form @submit.native.prevent>
        <el-form-item>
            <el-input clearable @clear="search" placeholder="请输入数据源名称" @keyup.enter.native="search" v-model="form.keyword">
                <i slot="prefix" class="iconfont icon-sousuo" v-preventReClick="2000" @click="search"></i>
            </el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handleAdd()">新增数据源</el-button>
        </el-form-item>
    </el-form>
    <div class="box-table">
        <el-table height="100%" v-loading="loading" :data="tableData" tooltip-effect="dark" :default-sort="{prop: 'lastUpdateTime', order: 'descending'}">
            <template slot="empty">
                <no-data :types="isSearch">
                    <span>暂无数据</span>
                </no-data>
            </template>
            <!-- <el-table-column label="数据库" prop="databaseName" show-overflow-tooltip></el-table-column> -->
            <el-table-column label="名称" prop="sourceName" show-overflow-tooltip></el-table-column>
            <el-table-column label="类型" show-overflow-tooltip>
                <template slot-scope="scope">{{['Mysql', 'DB2', 'Oracle'][scope.row.databaseType]}}</template>
            </el-table-column>
            <!-- <el-table-column label="系统" prop="databaseSchema" show-overflow-tooltip></el-table-column> -->
            <el-table-column label="主机" prop="databaseIp" show-overflow-tooltip></el-table-column>
            <el-table-column label="端口" prop="databasePort" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名" prop="databaseUser" show-overflow-tooltip></el-table-column>
            <el-table-column label="修改人" prop="lastUpdateOper" show-overflow-tooltip></el-table-column>
            <el-table-column label="修改时间" prop="lastUpdateTime" sortable show-overflow-tooltip min-width="110"></el-table-column>
            <el-table-column label="测试状态" show-overflow-tooltip>
                <template slot="header">
                    <span class="name">测试状态</span>
                    <!-- <el-tooltip effect="dark" content="系统每隔10分钟会自动尝试连接一次数据源，如果无法连通，则会显示连接失败的状态。" placement="top">
                        <span><i class="el-icon-question"></i></span>
                    </el-tooltip> -->
                </template>
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.databaseConnectivity===0" type="success">正常</el-tag>
                    <el-tag v-else type="danger">失效</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="130">
                <template slot-scope="scope">
                    <el-button type="text" @click="autoTest(scope.row)">重新连接</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" @click="handleAdd(scope.row)">修改</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" @click="handleRemove(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div v-if="tableData.length>0" class="box-pagenation">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
    <add-source v-if="addSource.show" :addForm="addSource" @save="saveAdd"></add-source>
</div>
</template>

<script>
import {
    mapGetters,
    mapMutations
} from 'vuex'
import AddSource from './Add'
import NoData from '@/components/NoData'
export default {
    name: 'SourceList',
    components: {
        AddSource,
        NoData
    },
    data () {
        return {
            sourceId: null,
            addSource: {
                show: false,
                title: '新增数据源',
                form: {
                    sourceName: null,
                    databaseType: null,
                    databaseIp: null,
                    databasePort: null,
                    databaseName: null,
                    databaseUser: null,
                    databasePwd: null,
                    description: null
                }
            },
            loading: false,
            form: {
                keyword: null,
                databaseType: null,
                databaseIp: null
            },
            total: 0,
            pageSize: 10,
            currentPage: 1,
            tableData: [],
            isSearch: false
        }
    },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId'
        })
    },
    mounted () {
        this.setHeaderBack('数据源管理')
        this.init()
    },
    methods: {
         ...mapMutations({
            setHeaderBack: 'common/setHeaderBack'
        }),
        // 新增数据源保存
        saveAdd (flag) {
            let params = {
                ...this.addSource.form,
                projectId: this.projectId
            }
            if (flag) {
                let url = ''
                if (this.sourceId) {
                    url = '/dataSource/updateDataSource'
                    params.sourceId = this.sourceId
                } else {
                    url = '/dataSource/addDataSource'
                }
                this.$post(url, params).then(res => {
                    this.init()
                    this.$message.success('保存成功')
                    this.addSource.show = false
                })
            } else {
                this.$post('/dataSource/preCheckDataSource', params).then(res => {
                    res ? this.$message.success('连接成功') : this.$message.error('连接失败')
                })
            }
        },
        // 新增、编辑提供测试功能
        handleAdd (item) {
            if (item) {
                const { sourceId, sourceName, databaseType, databaseIp, databasePort, databaseName, databaseUser, databasePwd, description } = item
                this.sourceId = sourceId
                this.addSource.title = '编辑数据源'
                this.addSource.form = {
                    sourceName,
                    databaseType,
                    databaseIp,
                    databasePort,
                    databaseName,
                    databaseUser,
                    databasePwd,
                    description
                }
            } else {
                this.sourceId = null
                this.addSource.title = '新增数据源'
                this.addSource.form = {
                    sourceName: null,
                    databaseType: null,
                    databaseIp: null,
                    databasePort: null,
                    databaseName: null,
                    databaseUser: '',
                    databasePwd: '',
                    description: null
                }
            }
            this.addSource.show = true
        },
        autoTest (item) {
            const params = {
                projectId: this.projectId,
                sourceId: item.sourceId
            }
            this.$post('/dataSource/checkDataSource', params).then(res => {
                res ? this.$message.success('连接成功') : this.$message.error('连接失败')
                this.init()
            })
        },
        search () {
            this.currentPage = 1
            this.isSearch = true
            this.init()
        },
        init () {
            this.loading = true
            const { databaseType, keyword, databaseIp } = this.form
            const params = {
                projectId: this.projectId,
                keyword,
                databaseType,
                databaseIp,
                pageSize: this.pageSize,
                pageNum: this.currentPage
            }
            this.$post('/dataSource/queryDataSources', params).then(res => {
                if (res) {
                    const {
                        total,
                        rows
                    } = res
                    this.total = total
                    this.tableData = rows
                }
            }).finally(() => {
                this.loading = false
            })
        },
        reset () {
            this.form = {
                databaseType: null,
                keyword: null,
                databaseIp: null
            }
            this.isSearch = false
            this.init()
        },
        handleRemove (item) {
            this.$confirm(`确定要删除数据源<span>[${item.sourceName}]</span>吗？`, '提示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                dangerouslyUseHTMLString: true,
                showClose: false,
                type: 'warning'
            }).then(() => {
                const params = {
                    projectId: this.projectId,
                    sourceIds: [item.sourceId]
                }
                this.$post('/dataSource/deleteDataSources', params).then(res => {
                    if (res) {
                        this.$message.success('删除成功')
                        this.init()
                    }
                })
            }).catch(() => {})
        },
        handleCurrentChange (val) {
            this.currentPage = val
            this.init()
        },
        handleSizeChange (val) {
            this.pageSize = val
            this.init()
        }
    },
    destroyed () {
        window.clearInterval(this.timer)
    }
}
</script>

<style lang="less">
.data-source {
    height: 100%;
    .el-form {
        display: flex;
        justify-content: space-between;
        .el-button {
            margin-left: 16px;
        }
    }
    .name {
        margin-right: 5px;
    }
    .icon-question {
        font-size: 13px;
    }
}
</style>
